// packageI/CouponShareShow/CouponShareShow.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: ['a'],
    showShare: false,
    info: [],
    avatar: '',
    posterLogo: '',
    posterName: '',
    qr_code: '',
    posterShow: false,
    loadingImg: false,
    logo: '',
    mark_id: '',
    mid: '',
    dataURL: '',
    fontSize: '',
    // is_belongs_to_coupon: '',
    isclick: false,
    nums: '',
    share_title:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
    if (options.id) {
      this.setData({
        couponId: options.id
      })
    }
    if (options.info) {
      this.setData({
        // info: options.info.info,
        nums:JSON.parse(options.info).couponNum,
        combine:JSON.parse(options.info).combine == 'false' ? 0 : 1,
      })
    } else {
      wx.navigateTo({
        url: '/packageG/index/index',
      })
      return
    }
    this.init();
    // 获取优惠券信息
    this.getdetail();
    wx.setNavigationBarTitle({
      title: '优惠券分享',
    })
    wx.getSystemInfo({
      success: (res) => {
        let unit = res.windowWidth / 375;
        let width = res.windowWidth;
        let myCanvasWidth = 343 * unit;
        let myCanvasHeight = 450 * unit;
        this.setData({
          canvasWidth: myCanvasWidth,
          canvasHeight: myCanvasHeight
        });
      }
    });
  },
  init() {
    this.setData({
      avatar: '',
      posterLogo: '',
      posterName: '',
      qr_code: '',
      loadingImg: false,
      posterShow: false,
      fontSize: 0,
      dataURL: ''
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var value = wx.getStorageSync("yz_uid");
    let name = wx.getStorageSync('nickname')
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title?this.data.share_title:`${name}向您分享${this.data.info.name}`,
      path: `/packageI/shareGet/shareGet?k=${this.data.mark_id}&mid=${mid}`
    };
  },
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    let name = wx.getStorageSync('nickname')
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title?this.data.share_title:`${name}向您分享${this.data.info.name}`,
      path: `/packageI/shareGet/shareGet?k=${this.data.mark_id}&mid=${mid}`
    };
  },
  getShareCoupons(){
    let urlStr = app.getNetAddresss("plugin.share-coupons.Frontend.controllers.share.getShareName");
    app._getNetWork({
      url: urlStr,
      data: { coupon_id: this.data.info.id, num: this.data.nums },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.data.share_title = res.data.share_title;
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getdata() {
    let json = {
      record_id: this.data.couponId,
      combine: this.data.combine,
      num: this.data.nums
    }
    let urlStr = app.getNetAddresss("plugin.share-coupons.Frontend.controllers.list.choose-coupon");
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res)
          this.setData({
            logo: res.data.logo,
            mark_id: res.data.mark_id
          })
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getdetail() {
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-detail");
    urlStr += "&record_id=" + this.data.couponId;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            info: res.data.coupon,
          })
          if (this.data.info.name.length >= 7) {
            this.setData({
              fontSize: '26rpx'
            })
          } else {
            this.setData({
              fontSize: '45rpx'
            })
          }
          this.getdata();
          this.getShareCoupons();
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getPoster() {
    if (this.data.isclick) return
    this.data.isclick = true;
    let urlStr = app.getNetAddresss("plugin.share-coupons.Frontend.controllers.list.poster");
    app._getNetWork({
      url: urlStr,
      data: {
        mark_id: this.data.mark_id
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            avatar: res.data.avatar,
            logo: res.data.logo,
            nickname: res.data.nickname,
            qr_code: res.data.qr_code,
            background: res.data.static_img,
          })
          this.cavVasMethod();
        } else {
          this.data.isclick = false
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  cavVasMethod() {
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        wx.showLoading({
          title: '加载中',
        })
        // Canvas 对象
        const canvas = res[0].node
        // 渲染上下文
        const ctx = canvas.getContext('2d')

        // Canvas 画布的实际绘制宽高
        const width = res[0].width
        const height = res[0].height

        // 初始化画布大小
        const dpr = 375/wx.getSystemInfoSync().windowWidth ;
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        let canvasWidthBox = (canvas.width * 0.15);
        await this.downImgae();
        ctx.restore()
        // 画背景
        await this.creatImg(this.data.background, ctx, canvas, canvas.width, canvas.height, 0, 0)
        ctx.restore()
        // 画头像
        let avatarWidth = 0 + (canvas.width * 0.05);
        let avatarHeight = (canvas.height - canvasWidthBox) - (canvas.width * 0.055);
        await this.creatImg(this.data.avatar, ctx, canvas, canvasWidthBox, canvasWidthBox, avatarWidth, avatarHeight);
        ctx.restore()
        ctx.font = "normal 13px Verdana";
        ctx.fillStyle = "#fff";
        await setTimeout(() => {
          if (this.data.nickname.length > 10) {
            this.data.nickname = this.data.nickname.slice(0, 9) + '...'
          }
          ctx.fillText(this.data.nickname, (canvasWidthBox * 0.4) + (canvasWidthBox), (canvas.height - canvasWidthBox));
          ctx.fillText("向你分享了优惠券", (canvasWidthBox * 0.4) + (canvasWidthBox), (canvas.height - (canvasWidthBox * 0.5)), 110);
          ctx.restore()
        }, 300);
        let canvasWidthBox2 = (canvas.width * 0.35);
        let qrcodeWidth = ((canvas.width - canvasWidthBox2) - (canvas.width * 0.05));
        let qrcodeHeight = ((canvas.height - canvasWidthBox2) - (canvas.width * 0.055))
        await setTimeout(() => {
          this.creatImg(this.data.qr_code, ctx, canvas, (canvasWidthBox2), (canvasWidthBox2), qrcodeWidth, qrcodeHeight);
        }, 400)
        ctx.restore()
        await setTimeout(() => {
          this.toimage(canvas, dpr)
        }, 1500);
      })
  },
  toimage(canv, dpr) {
    let that = this;
    wx.hideLoading();
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 580 * dpr,
      height: 814 * dpr,
      canvas: canv,
      destWidth: this.data.canvasWidth,
      destHeight: this.data.canvasHeight,
      quality: 1,
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(res)
        that.setData({
          tempFilePath: tempFilePath,
          loadingImg: true
        })
        that.data.isclick = false;
      },
      fail: function (res) {
        that.data.isclick = false;
      }
    });
  },
  closePopup() {
    this.setData({
      loadingImg: false
    })
  },
  creatImg(url, ctx, canvas, w, h, ptop, pleft) {
    return new Promise((resolve, reject) => {
      const image = canvas.createImage();
      let that = this;
      image.src = url
      image.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.drawImage(image, ptop, pleft, w, h)
          resolve(true)
        },
        image.onerror = () => {
          wx.hideLoading();
          that.data.isclick = false;
          resolve(false)
        }
    })

  },
  downImgae() {
    let that = this;
    if (that.data.background) {
      wx.downloadFile({
        url: this.data.background, // 服务器返回的图片地址
        success: (res) => {
          that.data.background = res.tempFilePath;
        },
        fail: (err) => {
          wx.hideLoading();
          that.data.isclick = false;
        }
      })
    }
    if (this.data.avatar) {
      wx.downloadFile({
        url: this.data.avatar, // 服务器返回的图片地址
        success: (res) => {
          that.data.avatar = res.tempFilePath;
        },
        fail: (err) => {
          wx.hideLoading();
          that.data.isclick = false;
        }
      })
    }

    if (that.data.qr_code) {
      wx.downloadFile({
        url: this.data.qr_code, // 服务器返回的图片地址
        success: (res) => {
          that.data.qr_code = res.tempFilePath;
        },
        fail: (err) => {
          wx.hideLoading();
          that.data.isclick = false;
        }
      })
    }
  }
})